package activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.thinkland.juheapi.common.JsonCallBack;
import com.thinkland.juheapi.data.weather.WeatherData;

import android.view.WindowManager.LayoutParams;
import android.widget.Toast;

import com.thinkland.juheapi.demo.R;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import Utils.ChineseCharToEn;
import Utils.SortCityName;
import adapter.CityListAdatper;
import view.SideBar;

/**
 * Created by Administrator on 15-11-30.
 */
public class CityActivity extends Activity implements SideBar.OnTouchingLetterChangedListener{
    private ListView lv_city;
    private List<String> list;
    //索引条
    private SideBar sideBar;
    //选择字体提示框
    private TextView dialogText;
    private WindowManager windowManager;
    //存储经过工具类获得的城市名称英文简写
    private List<String> listSoryKeys;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_city);
        initViews();
        getCities();

    }


    private void initViews() {
        findViewById(R.id.iv_back).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                finish();
            }
        });

        lv_city = (ListView) findViewById(R.id.lv_city);
        sideBar = (SideBar) findViewById(R.id.sideBar);
        sideBar.setOnTouchingLetterChangedListener(this);

        dialogText = (TextView) LayoutInflater.from(this).inflate(
                R.layout.city_select_remind, null);
        dialogText.setVisibility(View.INVISIBLE);

        windowManager = (WindowManager) this
                .getSystemService(Context.WINDOW_SERVICE);
        WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.TYPE_APPLICATION,
                WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
                        | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                PixelFormat.TRANSLUCENT);
        windowManager.addView(dialogText, lp);

        sideBar.setTextView(dialogText);

    }


    private void getCities() {
        final WeatherData data = WeatherData.getInstance();
        data.getCities(new JsonCallBack() {
            @Override
            public void jsonLoaded(JSONObject jsonObject) {
//                Log.i("TAG", jsonObject.toString());
                try {
                    int code = jsonObject.getInt("resultcode");
                    int error_code = jsonObject.getInt("error_code");
                    if (error_code == 0 && code == 200) {

                        list = new ArrayList<String>();
                        listSoryKeys = new ArrayList<String>();

                        JSONArray jsonArray = jsonObject.getJSONArray("result");
                        Set<String> citySet = new HashSet<String>();
                        for (int i = 0; i < jsonArray.length(); i++) {
                            String city = jsonArray.getJSONObject(i).getString("city");
                            citySet.add(city);
                        }

                        list.addAll(citySet);
                        //对List元素进行排序
                        Collections.sort(list, new SortCityName());
                        for (int i = 0; i < list.size(); i++) {
                            String sortKey = ChineseCharToEn.getFirstSpell(list.get(i));
//                            Log.i("TAG", sortKey);
                            listSoryKeys.add(sortKey);
                        }
                        CityListAdatper cityListAdapter = new CityListAdatper
                                (CityActivity.this, list, listSoryKeys);
                        lv_city.setAdapter(cityListAdapter);
                        lv_city.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                Intent intent = new Intent();
                                intent.putExtra("city", list.get(position));
                                setResult(1, intent);
                                finish();
                            }
                        });
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }


    @Override
    public void onTouchingLetterChanged(String s) {
        lv_city.setSelection(findCityIndex(list,s));
    }

    /**
     * 根据索引字母查询城市列表中第一次出现对映字母的index位置
     * @param list
     * @param s
     * @return
     */
    private int findCityIndex(List<String> list, String s) { if (list!=null){
            for (int i = 0; i < list.size(); i++) {
                //listSor
                if(s.equals(listSoryKeys.get(i).toUpperCase().charAt(0)+"")){
                    return i;
                }
            }
        }else{
            Toast.makeText(getApplicationContext(),"暂无信息", Toast.LENGTH_SHORT).show();
        }
        return -1;
    }

    @Override
    protected void onDestroy() {
        windowManager.removeView(dialogText);
        super.onDestroy();
    }
}
